//
//  USSetController.m
//  us
//
//  Created by karry on 2025/4/8.
//

#import "USSetController.h"
#import "USSetHeaderView.h"
#import "USAccountController.h"
#import "USDateAlertView.h"
@interface USSetController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,strong) UITableView *tableView;

@property (nonatomic,strong) USSetHeaderView *header;

@property (nonatomic,strong) NSArray <DTItem *>*items;

@end


@implementation USSetController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    [self reloadCharacter];
    [self reloadDay];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    //账户 - 解除匹配，手机号，注销账户，退出登陆
    //商店
    
    //设置 -
    //消息设置
    //指针设置
    //每日情话

    
    //信息
    //成为粉丝 - 推广进入我们的社交媒体
    //Us 信息 - 隐私安全之类
    //支持我们
    //应用版本 - 版本号
    [self setupData];
    [self setupView];
    
}

- (void)reloadCharacter {
    
    self.header.cv0.character = USUser.user.character;
    self.header.cv1.character = USUser.user.relCharacter;
    
}

- (void)reloadDay {
    NSMutableAttributedString *text1 = [[NSMutableAttributedString alloc]initWithString:@"Day+" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:28 weight:UIFontWeightMedium],NSForegroundColorAttributeName:UIColor.labelColor}];
    
    NSMutableAttributedString *text2 = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%li",USUser.user.metTimeDescription] attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:28 weight:UIFontWeightBold],NSForegroundColorAttributeName:UIColor.mainRedColor}];
    
    [text1 appendAttributedString:text2];
    
    self.header.lab.attributedText = text1;
    
    self.header.lab.hidden = USUser.user.relStatus == 0;
}

- (void)setupData{
    
    DTItem *g_item0 = [DTItem itemWithTitle:nil image:nil tag:0 identifier:@"user" handle:nil];
    {
        DTItem *account = [DTItem itemWithTitle:@"账户" image:[UIImage imageNamed:@"set_icon-0"] tag:0 identifier:@"account" handle:nil];
//        DTItem *store = [DTItem itemWithTitle:@"商店" image:[UIImage imageNamed:@"set_icon-1"] tag:0 identifier:@"store" handle:nil];
        DTItem *widget = [DTItem itemWithTitle:@"小组件" image:[UIImage imageNamed:@"set_icon-2"] tag:0 identifier:@"widget" handle:nil];
        g_item0.items = @[account,widget];
    }

    DTItem *g_item1 = [DTItem itemWithTitle:@"设置" image:nil tag:0 identifier:@"set" handle:nil];
    {
        
        DTItem *defaultSet = [DTItem itemWithTitle:@"偏好" image:[UIImage imageNamed:@"icon-1 2"] tag:0 identifier:@"defaultSet" handle:nil];
        
        DTItem *message = [DTItem itemWithTitle:@"消息" image:[UIImage imageNamed:@"set_icon-3"] tag:0 identifier:@"message" handle:nil];
        
        DTItem *pointer = [DTItem itemWithTitle:@"在哪儿？" image:[UIImage imageNamed:@"set_icon-4"] tag:0 identifier:@"pointer" handle:nil];
        
        DTItem *tarot = [DTItem itemWithTitle:@"我的塔罗牌" detailTitle:nil image:[UIImage imageNamed:@"icon 3"] tag:0 identifier:@"tarot" handle:nil];
        
        DTItem *launch = [DTItem itemWithTitle:@"us启动心动问候" image:[UIImage imageNamed:@"set_icon-9"] tag:0 identifier:@"launch" handle:nil];

        g_item1.items = @[defaultSet,message,pointer,tarot,launch];
        
    }
    
    DTItem *g_item2 = [DTItem itemWithTitle:@"信息" image:nil tag:0 identifier:@"info" handle:nil];
    {
        DTItem *fens = [DTItem itemWithTitle:@"成为粉丝" image:[UIImage imageNamed:@"set_icon-5"] tag:0 identifier:@"fens" handle:nil];
        DTItem *us = [DTItem itemWithTitle:@"us信息和策略" image:[UIImage imageNamed:@"set_icon-6"] tag:0 identifier:@"us" handle:nil];
        DTItem *supportUs = [DTItem itemWithTitle:@"支持us团队" image:[UIImage imageNamed:@"set_icon-7"] tag:0 identifier:@"supportUs" handle:nil];
        DTItem *sponsorUs = [DTItem itemWithTitle:@"赞助计划" image:[UIImage imageNamed:@"icon 1"] tag:0 identifier:@"sponsorUs" handle:nil];
        DTItem *version = [DTItem itemWithTitle:[NSString stringWithFormat:@"应用版本 %@",[self jk_version]] image:[UIImage imageNamed:@"set_icon-8"] tag:0 identifier:@"version" handle:nil];
        g_item2.items = @[fens,us,sponsorUs,supportUs,version];
    }
    self.items = @[g_item0,g_item1,g_item2];
    
}

- (void)setupView{
    
    self.tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    self.tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = UIColor.clearColor;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    
    USSetHeaderView *header = [USSetHeaderView jk_loadInstanceFromNib];
    self.header = header;
    @weakify(self)
    [header.cv0 jk_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
        @strongify(self)
        [USFeedbackTool impactSoft];
        [self.navigationController pushViewController:[NSClassFromString(@"USUserInfoViewController") new] animated:YES];
    }];
    
    [header.cv1 jk_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
        @strongify(self)
        [USFeedbackTool impactSoft];
        [self.navigationController pushViewController:[NSClassFromString(@"USUserInfoViewController") new] animated:YES];
    }];
    
    header.lab.userInteractionEnabled = YES;
    [header.lab jk_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
        @strongify(self)
        [USFeedbackTool impactSoft];

        NSDate *date = NSDate.date;
        if ([USUser user].metTime > 0) {
            date = [NSDate dateWithTimeIntervalSince1970:[USUser user].metTime];
        }
   
        USDateAlertView *alert = [[USDateAlertView alloc]initWithDate:date andSubTitle:@"设置我们认识的日子" limitToNow:YES];
        [alert showInView:UIViewController.topViewController.view];
        @weakify(self)
        alert.didChooseBlock = ^(NSDate * _Nonnull date) {
            @strongify(self)
             NSInteger timestampInSeconds = (NSInteger)[date timeIntervalSince1970];
            
            [self updateMetTime:timestampInSeconds];

         };
    }];
    
    [self reloadCharacter];
    [self reloadDay];
 
    header.backgroundColor  = UIColor.clearColor;
    header.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    
    UIView *contentView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.jk_width, 160)];
    [contentView addSubview:header];
    [header mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.mas_offset(0);
    }];
    
    self.tableView.tableHeaderView = contentView;

    
    
}

- (void)updateMetTime:(NSInteger)metTime{
    [USFeedbackTool notifySuccess];

    NSDictionary *params = @{
        @"relId" : @(USUser.user.relId),
        @"metTime" : @(metTime)
    };

    [[EMNetWork shareManager] em_post:API_EditUserRelationshlip
                               params:params
                                  hud:nil
                           showError:YES
                              success:^(EMApiModel *api) {
        [self.view endEditing:YES];
        
        if (!api.success) {
            return;
        }
        USUser *user = [USUser user];
        user.metTime = metTime;
        [USUser saveUser:user];

        [self reloadDay];
        
    } fail:^{
                
    }];
}
#pragma mark - tableview

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    DTItem *item = self.items[indexPath.section].items[indexPath.row];
    
    if ([item.identifier isEqualToString:@"account"]) {
        
        USAccountController *vc = [[USAccountController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
        
    }if ([item.identifier isEqualToString:@"widget"]) {
        
     
        MOAlertBaseView *alert = [[MOAlertBaseView alloc]initWithTitle:@"小组件功能" detailTitle:@"1.长按桌面空白区域，进入桌面编辑状态\n\n2.点击左上角“+”按钮\n\n3.找到「US」的小组件，点击“添加小组件”按钮" contentView:nil leftButtonImageName:nil rightButtonImageName:nil autoDissmiss:YES tapDissmiss:YES];
        alert.detailLabel.textAlignment = NSTextAlignmentLeft;
        
        [alert show];
    }else if ([item.identifier isEqualToString:@"pointer"]){
        [self.navigationController pushViewController:[NSClassFromString(@"USLoveCompassViewController") new] animated:YES];
    }else if ([item.identifier isEqualToString:@"message"]){
        [self.navigationController pushViewController:[NSClassFromString(@"USMessageSetController") new] animated:YES];
    }else if ([item.identifier isEqualToString:@"fens"]){
        [self.navigationController pushViewController:[NSClassFromString(@"USFensViewController") new] animated:YES];
    }else if ([item.identifier isEqualToString:@"us"]){
        [self.navigationController pushViewController:[NSClassFromString(@"USOurInfoViewController") new] animated:YES];
    }else if ([item.identifier isEqualToString:@"sponsorUs"]){
        [self.navigationController pushViewController:[NSClassFromString(@"USSponsorUsController") new] animated:YES];
    }else if ([item.identifier isEqualToString:@"tarot"]){
        [self.navigationController pushViewController:[NSClassFromString(@"USTarotCoverController") new] animated:YES];
    } else if ([item.identifier isEqualToString:@"supportUs"]){

        NSString *urlString = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/app/id%@?action=write-review", UsAppId];
        NSURL *url = [NSURL URLWithString:urlString];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
        }
        
    }else if ([item.identifier isEqualToString:@"defaultSet"]){
        [self.navigationController pushViewController:[NSClassFromString(@"USDefaultSettingController") new] animated:YES];
    }
    
   
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.items.count;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return self.items[section].items.count;
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    DTItem *g_item = self.items[section];
    
    if (g_item.title.length > 0) {
        UIView *view = [UIView new];
        UILabel *lab = [UILabel new];
        lab.font = [UIFont us_groupFont];
        lab.text = g_item.title;
        [view addSubview:lab];
        [lab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(view.mas_safeAreaLayoutGuideLeft).mas_offset(16);
            make.bottom.mas_offset(-2);
        }];
        return view;
    }
    
    UIView *v = [UIView new];
    return v;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    DTItem *g_item = self.items[section];
    if (g_item.title.length > 0) {
        return 30;
    }
    return 0.1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [UITableViewCell us_defaultCell];
    DTItem *item = self.items[indexPath.section].items[indexPath.row];
    
    cell.imageView.image = item.image;
    
    cell.textLabel.text = item.title;

    if ([item.identifier isEqualToString:@"supportUs"]) {
        
        [cell us_setAccessoryViewImage:[UIImage imageNamed:@"arrow_1"]];
        
    }else if ([item.identifier isEqualToString:@"launch"]){
        //心动问候
        [cell us_setAccessorySwitchisSelected:[[NSUserDefaults standardUserDefaults] boolForKey:USPrefKey_EnableStartupGreeting] action:^(BOOL selected) {
            [[NSUserDefaults standardUserDefaults]setBool:selected forKey:USPrefKey_EnableStartupGreeting];
        }];
        
    }else if([item.identifier isEqualToString:@"version"]){
        
        [cell us_setAccessoryViewImage:UIImage.new];
        
    }else{
        [cell us_setAccessoryViewImage:[UIImage imageNamed:@"arrow_0"]];
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 55;
}

@end
